Ext.extend(app.module,{
    currentFormValues: {},
    init: function(){
        var main = this;
        //用于列表
        this.ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'role/roles.do'}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'},
                {name:'description'}
            ])
        });
        this.treeLoader = new Ext.tree.TreeLoader({dataUrl:'menu/menus.do'});
        this.treeLoader.processResponse = function(response, node, callback){
            var json = response.responseText;
            try{
                var json = eval("(" + json + ")");
                node.beginUpdate();
                var o = json["key"];
                for(var i=0,len=o.length; i<len; i++){
                    var n = this.createNode(o[i]);
                    if(n){
                        node.appendChild(n);
                    }
                }
                node.endUpdate();
                if(typeof callback == "function"){
                    callback(this,node);
                }
            } catch(e) {
                this.handleFailure(response);
            }
        }
        var role_pagesize_combo = new Ext.form.ComboBox( {       //设置分页栏的每页记录数选择
            name : 'pagesize',
            hiddenName : 'pagesize',
            typeAhead : true,
            triggerAction : 'all',
            lazyRender : true,
            mode : 'local',
            store : new Ext.data.ArrayStore(
                {
                    fields : [ 'value', 'text' ],
                    data : [ [ 20, '20条/页' ],
                        [ 50, '50条/页' ], [ 100, '100条/页' ],
                        [ 250, '250条/页' ], [ 500, '500条/页' ] ]
                }),
            valueField : 'value',
            displayField : 'text',
            value : '20',
            editable : false,
            width : 85
        });
        var number = parseInt(role_pagesize_combo.getValue());

        role_pagesize_combo.on("select", function(comboBox) {
            var bbar = Ext.getCmp('rolebbar');
            bbar.pageSize = parseInt(comboBox.getValue());
            number = parseInt(comboBox.getValue());
            main.ds.reload( {
                params : {
                    start : 0,
                    limit : bbar.pageSize
                }
            });
        });

        this.sm = new Ext.grid.CheckboxSelectionModel();
        this.body = new Ext.grid.GridPanel({
            store: this.ds,
            region: 'center',
            loadMask: true,
            viewConfig:{
                forceFit:true
            },
            sm: this.sm,
            columns: [
                new Ext.grid.RowNumberer(),
                this.sm,
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'id',
                    header: 'id',
                    hidden: true
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'name',
                    header: '角色名称'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'description',
                    header: '备注'
                }
            ],
            tbar: {
                xtype: 'toolbar',
                items: [
                    {
                        text: '新增',
                        iconCls : 'btn-new',
                        scope: this,
                        handler: this.add
                    },
                    '-',
                    {
                        text: '修改',
                        iconCls : 'btn-edit',
                        scope: this,
                        handler: this.edit
                    },
                    '-',
                    {
                        text: '删除',
                        iconCls : 'btn-del',
                        scope: this,
                        handler: this.del
                    }
                ]
            },
            bbar: {
                id: 'rolebbar',
                xtype: 'paging',
                pageSize : number,
                store : this.ds,
                displayInfo : true,
                displayMsg : '显示{0}条到{1}条,共{2}条',
                emptyMsg : "没有符合条件的记录",
                items : [ '-', '&nbsp;&nbsp;', role_pagesize_combo ]
            }
        });
        this.main.add(this.body);
        this.main.doLayout();
        this.ds.load({
            params: {
                start:0,
                limit:20
            }
        });
    },
    getDialog: function(){
        this.form = this.getForm();
        this.roleMenuTree = new Ext.tree.TreePanel( {
            loader: this.treeLoader,
            root : {
                id: 0,
                text: '根节点',
                expanded: true
            },
            autoScroll : false,
            rootVisible : false,// 根节点是否可见
            animate : false,    // 展开,收缩动画
            useArrows : false,  // 是否使用箭头样式
            lines:false,        // 去掉树的线
            border : false,
            region:'center',
            title:'能够操作的菜单',
            autoScroll:true,
            border:true,
            enableAllCheck:true
        });

        var dlg = new Ext.Window({
            height: 500,
            width: 500,
            layout: 'border',
            buttonAlign: 'center',
            border: false,
            frame: true,
            title: '',
            modal: true,
            plain: true,
            resizable: false,
            items: [this.form,this.roleMenuTree],
            listeners: {
                scope: this,
                render: function(fp){
                    this.form.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = this.form.getForm();
                    f.setValues(this.currentFormValues);
                    f.clearInvalid();
                }
            },
            buttons: [
                {
                    text: '保存',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '取消',
                    scope: this,
                    handler: function() {
                        this.dlg.close();
                    }
                }
            ]
        });
        return dlg;
    },
    getForm: function() {
        var form = new Ext.form.FormPanel({
            title:'角色信息',
            collapsible: true,
            split: true,
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'role/save.do',
            region:'west',
            width: 130,
            labelWidth: 5,
            defaults: {
                anchor: '100%'
            },
            items: [
                {
                    id: 'roleId',
                    xtype: 'hidden',
                    name: 'id',
                    fieldLabel: 'Label'
                },
                {
                    xtype: 'displayfield',
                    value: '角色名称：',
                    width:110
                },
                {
                    id: 'roleName',
                    xtype: 'textfield',
                    name: 'name',
                    allowBlank: false,
                    emptyText: '角色名称不能为空',
                    width:110
                },
                {
                    xtype: 'displayfield',
                    value: '角色描述：',
                    width:110
                },
                {
                    id: 'roleDescription',
                    xtype: 'textarea',
                    name: 'description',
                    width:110
                }
            ]
        });
        return form;
    },
    submit: function(){
        if (this.form.getForm().isValid()) {
            var id = this.form.getForm().findField("id").getValue();
            var menuIds = this.roleMenuTree.getChecked("id");
            this.form.getForm().submit({
                waitTitle: '保存数据',
                waitMsg: '正在保存……',
                scope: this,
                method: 'post',
                params: {menuIds:menuIds.join(",")},
                submitEmptyText: false,     //禁止提交emptyText
                success: function(form, action) {
                    var info = action.result.info;
                    if (action.result.success) {
                        this.ds.reload();
                        this.sm.clearSelections();
                        this.dlg.close();
                    }
                    Ext.Msg.alert('信息', info);
                },
                failure: function(form, action) {
                    var info = action.result.info;
                    Ext.Msg.alert('提示', info);
                }
            });
        }
    },
    add: function() {
        this.dlg = this.getDialog();
        Ext.apply(this.currentFormValues, {
            id: '',
            name: ""
        });
        this.dlg.setTitle("增加角色");
        this.dlg.show();
    },

    edit: function() {
        main = this;
        var recs = this.body.getSelectionModel().getSelections();
        Ext.apply(this.currentFormValues, {
            id: recs[0].data.id,
            name: recs[0].data.name,
            description: recs[0].data.description
        });
        if (recs.length==0) {
            Ext.Msg.alert('信息', '请选择要编辑的角色。');
        } else if(recs.length>1) {
            Ext.Msg.alert('信息', '只能选择一个角色进行编辑。');
        } else {
            this.dlg = this.getDialog();
            //勾选在窗口显示出来后再发生
            this.dlg.on('show', function() {
                Ext.Ajax.request({
                    method:'post',
                    url:'role/getMenuIdsByRole.do',
                    params:{id:recs[0].data.id},
                    scope: main,
                    success: function(resp, opts) {
                        var result = Ext.util.JSON.decode(resp.responseText);
                        var info = result.info;
                        if(result.success=='true') {
                            var menuids = result.menuids.split(",");
                            main.roleMenuTree.checkAllNodes(false);
                            Ext.each(menuids, function(n){
                                main.roleMenuTree.getNodeById(n).getUI().toggleCheck(true);
                            },this);
                        }else {
                            Ext.Msg.alert('信息', info);
                        }
                    },
                    failure: function(resp,opts) {
                        var result = Ext.util.JSON.decode(resp.responseText);
                        var info = result.info;
                        Ext.Msg.alert('提示', info);
                    }
                });
            });
            this.dlg.setTitle("编辑角色");
            this.dlg.show();
        }
    },

    del: function() {
        var main = this;
        if (this.body.getSelectionModel().hasSelection()) {
            var recs = this.body.getSelectionModel().getSelections();
            var ids = [];
            var titles = [];
            for (var i = 0; i < recs.length; i++) {
                var data = recs[i].data;
                ids.push(data.id);
                titles.push(data.name);
            }
            Ext.Msg.confirm('删除角色', '确定删除以下角色？<br><font color="red">' + titles.toString() + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        Ext.Ajax.request({
                            method:'post',
                            url:'role/remove.do',
                            params:{
                                ids:ids.toString()
                            },
                            scope: main,
                            success: function(resp, opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                if(result.success=='true') {
                                    this.ds.reload();
                                    Ext.Msg.alert('信息', info);
                                }else {
                                    Ext.Msg.alert('信息', info);
                                }
                            },
                            failure: function(resp,opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                Ext.Msg.alert('提示', info);
                            }
                        });
                    }
                });
        } else {
            Ext.Msg.alert('信息', '请选择要删除的角色！');
        }
    }
});